package com.hxgis.oc.util;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Optional;

public class ResponseHelper {
    public static HttpHeaders createFileHeader(String fileName,long length){
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        headers.add(HttpHeaders.CONTENT_LENGTH, Long.toString(length));
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.add(HttpHeaders.CACHE_CONTROL, "max-age=604800");
        String disposition;
        try {
            disposition = "filename=" + URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        Optional<MediaType> mediaType = MediaTypeFactory.getMediaType(fileName);
        if(mediaType.isPresent()){
            headers.add(HttpHeaders.CONTENT_TYPE, mediaType.get().toString());
        }else{
            disposition = "attachment;" + disposition;
        }
        headers.add(HttpHeaders.CONTENT_DISPOSITION, disposition);

        return headers;
    }
}
